import axios from 'axios'
import Vue from 'vue'
import util from './util'

let httpRequest = function (config) {
  let p = new Promise(function (resolve, reject) {
    config.baseURL = Vue.prototype.serverUrl
    config.withCredentials = true
    config.method = config.method || 'post'
    if (config.data !== null && typeof (config.data) === 'string' && config.method === 'post') {
      config.headers = config.headers || {}
      config.headers['content-type'] = config.headers['content-type'] || 'application/json;charset=UTF-8'
    }
    if (config.data !== null && typeof (config.data) === 'object') {
      let dst = {}
      util.shallowCopy(config.data, dst, {ignoreNullField: true})
      config.data = dst
    }
    config.loading = config.loading || {}
    config.loading.loading = true
    axios(config).then(res => {
      if (res.data.header !== '0') {
        resolve(res.data.data)
      } else {
        console.log(res)
        alert(res.data.header.msg)
        reject(res)
      }
    }).catch(err => {
      console.log(err)
      alert(err)
    }).then(() => {
      config.loading.loading = false
    })
  })
  return p
}

export default httpRequest
